﻿#include "mainwindow.h"
#include "ui_mainwindow.h"


MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    init();
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::init()
{
//    this->setCentralWidget(ui->stackedWidget);
    ui->tvDate->setEditTriggers(QAbstractItemView::NoEditTriggers);
    ui->tbStaData->setEditTriggers(QAbstractItemView::NoEditTriggers);
    ui->actStaData->setEnabled(false);
    ui->actHistogram->setEnabled(false);
    ui->actLineChart->setEnabled(false);
    ui->actPieChart->setEnabled(false);
    ui->actSave->setEnabled(false);

    m_dataModel = new QStandardItemModel(this);
    m_dataModel->insertColumn(m_dataModel->rowCount());

    m_staModel = new QStandardItemModel(this);

    ui->tvDate->setModel(m_dataModel);
    ui->tvDate->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);

    ui->tbStaData->setModel(m_staModel);
    ui->tbStaData->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);

    m_labFilePath.setText("当前文件路径:");
    m_labCurPosition.setText("当前位置:折线图");
    ui->statusbar->addWidget(&m_labFilePath,1);
    ui->statusbar->addWidget(&m_labCurPosition);


}

void MainWindow::staData()
{
    m_staModel->clear();
    m_staModel->setRowCount(7);
    m_staModel->setColumnCount(m_dataModel->rowCount());
    m_staModel->setData(m_staModel->index(1,0),"平均值");
    m_staModel->setData(m_staModel->index(2,0),"最大值");
    m_staModel->setData(m_staModel->index(3,0),"最小值");
    m_staModel->setData(m_staModel->index(4,0),"极差");
    m_staModel->setData(m_staModel->index(5,0),"方差");
    m_staModel->setData(m_staModel->index(6,0),"总和");
    for(int i = 1;i < m_staModel->columnCount();++i){
        m_staModel->setData(m_staModel->index(0,i),m_dataModel->data(m_dataModel->index(i,0)));
    }


    for(int i = 1;i < m_dataModel->rowCount();++i){
        int count = 0;
        double average = 0;
        int max = 0;
        int min = m_dataModel->data(m_dataModel->index(i,1)).toInt();
        int range = 0;
        double variance = 0;
        int total = 0;
        QList<int> valueList;

        for(int j = 1;j < m_dataModel->columnCount();++j){
            int value = m_dataModel->data(m_dataModel->index(i,j)).toInt();
            ++count;
            total += value;
            max = max > value ? max :value;
            min = min < value ? min :value;
            valueList.append(value);
        }
        average = (double)total / count;
        range = max - min;

        double staDev = 0;
        for(int n = 0; n < valueList.count(); ++n){
            staDev += qAbs(valueList.at(n) - average) * qAbs(valueList.at(n) - average);
        }
        variance = staDev / count;

        m_staModel->setData(m_staModel->index(1,i),QString::asprintf("%.1f",average));
        m_staModel->setData(m_staModel->index(2,i),max);
        m_staModel->setData(m_staModel->index(3,i),min);
        m_staModel->setData(m_staModel->index(4,i),range);
        m_staModel->setData(m_staModel->index(5,i),QString::asprintf("%.2f",variance));
        m_staModel->setData(m_staModel->index(6,i),total);

    }
}

void MainWindow::updateLineChart()
{
    m_labCurPosition.setText("折线图");
    m_chart = new QChart();
    m_chart->setTitle("折线图");
    QCategoryAxis* axisX = new QCategoryAxis();
    axisX->append("一月",0);
    axisX->append("二月",1);
    axisX->append("三月",2);
    axisX->append("四月",3);
    axisX->append("五月",4);
    axisX->append("六月",5);
    axisX->setLabelsPosition(QCategoryAxis::AxisLabelsPositionOnValue);

    QValueAxis* axisY = new QValueAxis;
    axisY->setMax(700);
    axisY->setMin(0);
    axisY->setMinorTickCount(1);
    axisY->setTickCount(8);

    for(int i = 1; i < m_dataModel->rowCount();++i){
        QLineSeries* line = new QLineSeries;
        line->setName(m_dataModel->data(m_dataModel->index(i,0)).toString());
        line->append(0,m_dataModel->data(m_dataModel->index(i,1)).toInt());
        line->append(1,m_dataModel->data(m_dataModel->index(i,2)).toInt());
        line->append(2,m_dataModel->data(m_dataModel->index(i,3)).toInt());
        line->append(3,m_dataModel->data(m_dataModel->index(i,4)).toInt());
        line->append(4,m_dataModel->data(m_dataModel->index(i,5)).toInt());
        line->append(5,m_dataModel->data(m_dataModel->index(i,6)).toInt());
        m_chart->addSeries(line);
        m_chart->setAxisX(axisX,line);
        m_chart->setAxisY(axisY,line);
    }

    ui->graphicsView->setChart(m_chart);
}


void MainWindow::on_actOpenExcel_triggered()
{
    QString filePath = QFileDialog::getOpenFileName(0,"选择文件",QCoreApplication::applicationDirPath(),"EXCEL文件(*.xls *.xlsx);;所有文件(*.*)");
    QFile file(filePath);
    if(file.exists()){
        QFileInfo info(file);
        if(info.suffix() == "xlsx" || info.suffix() == "xls"){
            ui->tvDate->setEditTriggers(QAbstractItemView::SelectedClicked);
            ui->actStaData->setEnabled(true);
            ui->actHistogram->setEnabled(true);
            ui->actLineChart->setEnabled(true);
            ui->actPieChart->setEnabled(true);
            ui->actSave->setEnabled(true);

            m_labFilePath.setText("当前文件路径:"+filePath);
            m_dataModel->clear();
            m_dataModel->insertColumn(m_dataModel->rowCount());


            m_axObject = new QAxObject("Excel.Application");
            m_axObject->dynamicCall("SetVisible (bool Visible)",false);
            m_axObject->setProperty("DisplayAlerts", false);

            QAxObject *workbooks = m_axObject->querySubObject("WorkBooks");
            QAxObject* workbook = workbooks->querySubObject("Open(const QString&)",filePath);

            QAxObject* worksheets = workbook->querySubObject("Sheets");
            QAxObject *worksheet = worksheets->querySubObject("Item(int)",1);
            QAxObject* usedrange = worksheet->querySubObject("UsedRange");
            int row = usedrange->querySubObject("Rows")->property("Count").toInt();
            int col = usedrange->querySubObject("Columns")->property("Count").toInt();

            for(int i = 0; i < row;++i){

                m_dataModel->insertRow(m_dataModel->rowCount());
                for(int j = 0;j < col;++j){

                    QString value = worksheet->querySubObject("Cells(int, int)",i+1,j+1)->property("Value").toString();
                    if(!value.isNull() && !value.isEmpty()){
                        if(i == 0){
                            m_dataModel->insertColumn(m_dataModel->columnCount());
                        }
                        m_dataModel->setData(m_dataModel->index(i,j),value);
                    }
                }
            }

            usedrange->deleteLater();
            worksheet->deleteLater();
            worksheets->deleteLater();
            workbook->deleteLater();
            workbooks->deleteLater();
            m_axObject->deleteLater();

            staData();
            updateLineChart();
        }else{
            QMessageBox::warning(0,"警告","选择文件不是excel文件.");
        }
    }
}


void MainWindow::on_actStaData_triggered()
{
    staData();
}


void MainWindow::on_actOpenTxt_triggered()
{
    QString filePath = QFileDialog::getOpenFileName(0,"选择文件",QCoreApplication::applicationDirPath(),"TXT文件(*.txt);;所有文件(*.*)");
    QFile file(filePath);
    if(file.exists()){
        QFileInfo info(file);
        if(info.suffix() == "txt"){
            ui->tvDate->setEditTriggers(QAbstractItemView::CurrentChanged);
            ui->actStaData->setEnabled(true);
            ui->actHistogram->setEnabled(true);
            ui->actLineChart->setEnabled(true);
            ui->actPieChart->setEnabled(true);
            ui->actSave->setEnabled(true);
            m_labFilePath.setText("当前文件路径:"+filePath);
            m_dataModel->clear();
            m_dataModel->insertColumn(m_dataModel->rowCount());


            file.open(QIODevice::ReadOnly);
            QTextStream stream(&file);
            for(;!stream.atEnd();){
                QString line = stream.readLine();
                QStringList lineList = line.split("\t");
                m_dataModel->setColumnCount(lineList.count());
                m_dataModel->insertRow(m_dataModel->rowCount());
                for(int j = 0;j <  lineList.count();++j){
                    m_dataModel->setData(m_dataModel->index(m_dataModel->rowCount() - 1,j),lineList.at(j));
                }
            }
            file.close();
            staData();
            updateLineChart();
        }
    }
}


void MainWindow::on_actLineChart_triggered()
{
    updateLineChart();
}


void MainWindow::on_actHistogram_triggered()
{
    m_labCurPosition.setText("柱状图");
    m_chart = new QChart();
    m_chart->setTitle("柱状图");
    QBarSet* set1 = new QBarSet("A");
    QBarSet* set2 = new QBarSet("B");
    QBarSet* set3 = new QBarSet("C");
    QBarSet* set4 = new QBarSet("D");
    QBarSet* set5 = new QBarSet("E");


    for(int i = 1; i < m_dataModel->columnCount();++i){
        set1->append(m_dataModel->data(m_dataModel->index(1,i)).toInt());
        set2->append(m_dataModel->data(m_dataModel->index(2,i)).toInt());
        set3->append(m_dataModel->data(m_dataModel->index(3,i)).toInt());
        set4->append(m_dataModel->data(m_dataModel->index(4,i)).toInt());
        set5->append(m_dataModel->data(m_dataModel->index(5,i)).toInt());

    }

    QBarSeries* barSeries1 = new QBarSeries;
    barSeries1->append(set1);
    barSeries1->append(set2);
    barSeries1->append(set3);
    barSeries1->append(set4);
    barSeries1->append(set5);

    m_chart->addSeries(barSeries1);
    QBarCategoryAxis* axisX = new QBarCategoryAxis;
    QStringList xLabels;
    xLabels << "一月" << "二月" << "三月" << "四月" << "五月" << "六月";
    axisX->append(xLabels);
    m_chart->setAxisX(axisX,barSeries1);
    axisX->setRange(xLabels.at(0),xLabels.last());
    QValueAxis* axisY = new QValueAxis;
    axisY->setRange(0,700);
    axisY->setTickCount(8);
    m_chart->setAxisY(axisY,barSeries1);



    ui->graphicsView->setChart(m_chart);
}


void MainWindow::on_actPieChart_triggered()
{
    m_labCurPosition.setText("饼状图");
    m_chart = new QChart();
    m_chart->setTitle("饼状图");
    QMap<QString,int> data;
    data.insert("A",m_staModel->data(m_staModel->index(6,1)).toInt());
    data.insert("B",m_staModel->data(m_staModel->index(6,2)).toInt());
    data.insert("C",m_staModel->data(m_staModel->index(6,3)).toInt());
    data.insert("D",m_staModel->data(m_staModel->index(6,4)).toInt());
    data.insert("E",m_staModel->data(m_staModel->index(6,5)).toInt());


    QPieSeries* pieSeries = new QPieSeries;
    int total = 0;
    for(int i = 0;i < data.count();++i){
        total += data.values().at(i);
    }

    QPieSlice* slice;
    for(int i = 0;i < data.count();++i){
        slice = new QPieSlice(data.keys().at(i)+QString::asprintf(" %.2f%%",data.values().at(i)/(double)total*100),data.values().at(i)/(double)total);
        pieSeries->append(slice);

    }
    pieSeries->setLabelsVisible(true);

    m_chart->addSeries(pieSeries);

    ui->graphicsView->setChart(m_chart);
}


void MainWindow::on_actSave_triggered()
{
    QString savePath = QFileDialog::getExistingDirectory(0,"选择文件夹",QCoreApplication::applicationDirPath());
    QDir dir(savePath);
    if(dir.exists()){
        QScreen* screen = QGuiApplication::primaryScreen();
        QPixmap p = screen->grabWindow(ui->graphicsView->winId());
        QImage img = p.toImage();
        img.save(savePath+"\\"+"mysave.jpg");
    }else{
        QMessageBox::warning(0,"警告","文件夹不存在.");
    }
}

